﻿/*
 * Tác giả: vucuongkg tổng hợp từ nhiều anh em khác, anh em nào thấy hàm nào của mình thì vào nhận nhé. :D
 * File này chứa phương thức tiện ích thực hiện các chức năng chung
 * Ngày tạo: 19/09/2012
 *
 */
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
using System.Collections.Generic;
using Ext.Net;

/// <summary>
/// Summary description for Util 
/// </summary>
public class Util
{
    #region Thông báo

    public static void ShowMessage(string title, string message)
    {
        Notification.Show(new NotificationConfig
        {
            Title = title,
            Icon = Icon.Information,
            Height = 80,
            CloseVisible = true,
            Width = 180,
            BodyStyle = "padding:10px",
            Html = message,
            ShowFx = new SlideIn { Anchor = AnchorPoint.Right },
            HideFx = new SlideOut { Anchor = AnchorPoint.Right }
        });
    }

    public static void ShowMessage(NotificationConfig config)
    {
        X.Msg.Hide();
        Notification.Show(config);
    }

    public static void ShowMessage(string message)
    {
        Notification.Show(new NotificationConfig
        {
            Title = "Thông báo",
            Icon = Icon.Information,
            Height = 80,
            CloseVisible = true,
            Width = 180,
            BodyStyle = "padding:10px",
            Html = message,
            ShowFx = new SlideIn { Anchor = AnchorPoint.Right },
            HideFx = new SlideOut { Anchor = AnchorPoint.Right }
        });
    }

    public static void ShowMessage2(string message)
    {
        Notification.Show(new NotificationConfig
        {
            Title = "Thông báo",
            Icon = Icon.Information,
            Height = 260,
            Width = 360,
            CloseVisible = true,
            AutoHide = false,
            BodyStyle = "padding:10px",
            Html = message,
            ShowFx = new SlideIn { Anchor = AnchorPoint.Right },
            HideFx = new SlideOut { Anchor = AnchorPoint.Right }
        });
    }

    public static void ShowMessage(string title, string message, int width, int height)
    {
        Notification.Show(new NotificationConfig
        {
            Title = title,
            Icon = Icon.Information,
            Height = height,
            Width = width,
            BodyStyle = "padding:10px",
            CloseVisible = true,
            Html = message,
            ShowFx = new SlideIn { Anchor = AnchorPoint.Right },
            HideFx = new SlideOut { Anchor = AnchorPoint.Right }
        });
    }

    public static void ShowMessage(string title, string message, int width, int height, bool autoHide)
    {
        Notification.Show(new NotificationConfig
        {
            Title = title,
            Icon = Icon.Information,
            Height = height,
            Width = width,
            BodyStyle = "padding:10px",
            Html = message,
            AutoHide = autoHide,
            Closable = true,
            CloseVisible = true,
            ShowFx = new SlideIn { Anchor = AnchorPoint.Right },
            HideFx = new SlideOut { Anchor = AnchorPoint.Right }
        });
    }
    #endregion

    #region Seo
    public static string BuildSEO(string convertedString)
    {

        string subject = convertedString.Trim();

        if (subject.Length > 250)
            subject = subject.Substring(0, 200);

        Regex regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");
        string strFormD = subject.Normalize(System.Text.NormalizationForm.FormD);
        subject = regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');

        subject = Regex.Replace(subject, @"\s+", "-");
        subject = Regex.Replace(subject, @"[^A-Za-z0-9_-]", "");
        subject = Regex.Replace(subject, @"-", " ");


        return subject;
    }

    public static string BuildSEO(object stringObject)
    {
        if (stringObject == null) return "";
        return BuildSEO(stringObject.ToString());
    }


    #endregion

    #region HTML

    public static string BoolableToString(bool? boolValue)
    {
        if (boolValue.HasValue)
        {
            if (boolValue.Value)
            {
                return "C\x00f3";
            }
            return "Kh\x00f4ng";
        }
        return "Kh\x00f4ng";
    }

    /// <summary>
    /// Lấy toàn bộ link ảnh trong 1 đoạn HTML
    /// </summary>
    /// <param name="source"></param>
    /// <returns></returns>
    public static List<string> GetAllImageLinks(string source)
    {
        List<string> links = new List<string>();
        string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
        MatchCollection matchesImgSrc = Regex.Matches(source, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        foreach (Match m in matchesImgSrc)
        {
            string href = m.Groups[1].Value;
            links.Add(href);
        }
        return links;
    }



    /// <summary>
    /// Remove HTML from string with Regex.
    /// </summary>
    public static string StripTagsRegex(string source)
    {
        return Regex.Replace(source, "<.*?>", string.Empty);
    }



    /// <summary>
    /// Remove HTML from string with Regex.
    /// </summary>
    public static string StripTagsRegex(object source)
    {
        string s = source.ToString();
        if (!string.IsNullOrEmpty(s))
        {
            return Regex.Replace(s, "<.*?>", string.Empty);
        }
        return "";
    }
    /// <summary>
    /// Xoa toan bo ki tu dac biet trong content
    /// Tuannv
    /// </summary>
    /// <param name="content"></param>
    /// <returns></returns>
    public static string ReplaceCharacterSpecial(string content)
    {
        string reg = @"[^\w\d\.]+";
        return Regex.Replace(content, reg, "_");
    }


    #endregion

    #region Add dot

    public static string AddDot(object price)
    {
        if (price == null) return "";
        return String.Format("{0:#,#}", Convert.ToDouble(price)).Replace(",", ".");
    }
    #endregion

    #region String operator
    /// <summary>
    /// Cắt chuối dài 
    /// </summary>
    /// <param name="content"></param>
    /// <param name="limit"></param>
    /// <returns></returns>
    public static string ShortentString(object content, int limit)
    {

        string result = "";
        string temp = "";
        string[] stringArray;
        temp = content.ToString();


        if (string.IsNullOrEmpty(temp)) return "";
        stringArray = temp.Split(" ".ToCharArray());

        if (stringArray.Length > limit)
        {
            for (int i = 0; i < limit; i++)
            {
                result = string.Concat(result, stringArray[i], " ");
            }
            result = string.Concat(result, "...");
            return result;
        }
        else
        {
            return temp;
        }
    }

    public static string ShortentString2(object content, int limit)
    {
        string contentValue = Convert.ToString(content);
        if (contentValue.Length < limit)
        {
            return contentValue;
        }
        contentValue = contentValue.Substring(0, limit);
        int iLastDot = contentValue.LastIndexOf(' ');
        return contentValue.Substring(0, iLastDot) + "...";
    }

    #endregion

    #region  Datetime
    public static string GetDateTime()
    {
        string datetime = "";
        string format = "{0}, ngày {1}";
        if (DateTime.Now.DayOfWeek == DayOfWeek.Sunday)
        {
            datetime = string.Format(format, "Chủ nhật", string.Format("{0:dd/MM/yyyy}", DateTime.Now));
        }
        if (DateTime.Now.DayOfWeek == DayOfWeek.Monday)
        {
            datetime = string.Format(format, "Thứ hai", string.Format("{0:dd/MM/yyyy}", DateTime.Now));
        }
        if (DateTime.Now.DayOfWeek == DayOfWeek.Tuesday)
        {
            datetime = string.Format(format, "Thứ ba", string.Format("{0:dd/MM/yyyy}", DateTime.Now));
        }
        if (DateTime.Now.DayOfWeek == DayOfWeek.Wednesday)
        {
            datetime = string.Format(format, "Thứ tư", string.Format("{0:dd/MM/yyyy}", DateTime.Now));
        }
        if (DateTime.Now.DayOfWeek == DayOfWeek.Thursday)
        {
            datetime = string.Format(format, "Thứ năm", string.Format("{0:dd/MM/yyyy}", DateTime.Now));
        }
        if (DateTime.Now.DayOfWeek == DayOfWeek.Friday)
        {
            datetime = string.Format(format, "Thứ sáu", string.Format("{0:dd/MM/yyyy}", DateTime.Now));
        }
        if (DateTime.Now.DayOfWeek == DayOfWeek.Saturday)
        {
            datetime = string.Format(format, "Thứ bảy", string.Format("{0:dd/MM/yyyy}", DateTime.Now));
        }
        return datetime;
    }

    public static string GetDateTime(object dt)
    {
        DateTime dtttt = Convert.ToDateTime(dt);
        string datetime = "";
        string format = "{0} {1}";
        if (dtttt.DayOfWeek == DayOfWeek.Sunday)
        {
            datetime = string.Format(format, "Chủ nhật, ", string.Format("{0:dd/MM/yyyy | h:hh}", dtttt));
        }
        if (dtttt.DayOfWeek == DayOfWeek.Monday)
        {
            datetime = string.Format(format, "Thứ hai, ", string.Format("{0:dd/MM/yyyy | h:hh}", dtttt));
        }
        if (dtttt.DayOfWeek == DayOfWeek.Tuesday)
        {
            datetime = string.Format(format, "Thứ ba, ", string.Format("{0:dd/MM/yyyy | h:hh}", dtttt));
        }
        if (dtttt.DayOfWeek == DayOfWeek.Wednesday)
        {
            datetime = string.Format(format, "Thứ tư, ", string.Format("{0:dd/MM/yyyy | h:hh}", dtttt));
        }
        if (dtttt.DayOfWeek == DayOfWeek.Thursday)
        {
            datetime = string.Format(format, "Thứ năm, ", string.Format("{0:dd/MM/yyyy | h:hh}", dtttt));
        }
        if (dtttt.DayOfWeek == DayOfWeek.Friday)
        {
            datetime = string.Format(format, "Thứ sáu, ", string.Format("{0:dd/MM/yyyy | h:hh}", dtttt));
        }
        if (dtttt.DayOfWeek == DayOfWeek.Saturday)
        {
            datetime = string.Format(format, "Thứ bảy, ", string.Format("{0:dd/MM/yyyy | h:hh}", dtttt));
        }
        return datetime;
    }

    public static DateTime GetStartWeek(DateTime currentDate)
    {



        int cachSoNgay = 0;
        switch (currentDate.DayOfWeek)
        {
            case DayOfWeek.Tuesday:
                cachSoNgay = 1;
                break;
            case DayOfWeek.Wednesday:
                cachSoNgay = 2;
                break;
            case DayOfWeek.Thursday:
                cachSoNgay = 3;
                break;
            case DayOfWeek.Friday:
                cachSoNgay = 4;
                break;
            case DayOfWeek.Saturday:
                cachSoNgay = 5;

                break;
            case DayOfWeek.Sunday:
                cachSoNgay = 6;
                break;
        }

        return currentDate.AddDays(-cachSoNgay);
    }

    public static int GetCountDaysInMonth(int month, int year)
    {
        int ketqua = 0;
        switch (month)
        {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                ketqua = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                ketqua = 30;
                break;
            case 2:
                if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
                    ketqua = 29;

                ketqua = 28;
                break;
        }
        return ketqua;

    }

    public static DateTime GetFirstDateInYear(int year)
    {
        DateTime firstDate = GetStartWeek(new DateTime(year, 1, 1));

        DateTime dateTemp = new DateTime(year, 1, 1);
        bool isTemp = false;
        switch (dateTemp.DayOfWeek)
        {
            case DayOfWeek.Thursday:
            case DayOfWeek.Friday:
            case DayOfWeek.Saturday:
            case DayOfWeek.Sunday:
                isTemp = true;
                break;
        }

        if (isTemp)
        {
            return firstDate.AddDays(7);
        }

        return firstDate;
    }

    public static int GetiCountWeekByMonday(DateTime dMonday)
    {
        //DateTime firstDate = GetStartWeek(new DateTime(dMonday.Year, 1, 1));
        DateTime firstDate = GetFirstDateInYear(DateTime.Now.Year);

        //DateTime currentDate = GetStartWeek(DateTime.Now);
        int sotuan = (dMonday - firstDate).Days / 7;
        return (sotuan + 1);

    }

    public static int GetNumberOfWeekInYear(int year)
    {
        int numberOfWeek = 52;
        if (!DateTime.IsLeapYear(year))
        {
            DateTime dateTime = new DateTime(year, 1, 1);
            if (dateTime.DayOfWeek == DayOfWeek.Thursday)
            {
                numberOfWeek = 53;
            }
        }
        else
        {
            DateTime dateTime = new DateTime(year, 1, 1);
            if (dateTime.DayOfWeek == DayOfWeek.Thursday || dateTime.DayOfWeek == DayOfWeek.Wednesday)
            {
                numberOfWeek = 53;
            }
        }
        return numberOfWeek;
    }

    public static DateTime FirstDayOfMonthFromDateTime(DateTime dateTime)
    {
        return new DateTime(dateTime.Year, dateTime.Month, 1);
    }

    public static DateTime LastDayOfMonthFromDateTime(DateTime dateTime)
    {
        DateTime firstDayOfTheMonth = new DateTime(dateTime.Year, dateTime.Month, 1);
        return firstDayOfTheMonth.AddMonths(1).AddDays(-1);
    }

    public static DateTime? ConvertHandlerDateTimeFormat(string date)
    {
        if (string.IsNullOrEmpty(date)) return null;
        try
        {
            date = date.Split('T')[0];
            return DateTime.Parse(date);
        }
        catch { }
        return null;
    }


    #endregion


    #region Xác định nguyên âm
    public static string XacDinhNguyenAm(string searchKey)
    {
        searchKey = searchKey.ToLower();
        char[] charArr = searchKey.ToCharArray();
        searchKey = "";
        foreach (char c in charArr)
        {
            string tmp = "";
            tmp = c.ToString();

            if (c == 'a')
            {
                tmp = "[aáàạảãâấầậẩẫăắằặẳẵ]";
            }
            if (c == 'e')
            {
                tmp = "[eéèẹẻẽêếềệểễ]";
            }
            if (c == 'o')
            {
                tmp = "[oóòọỏõôốồộổỗơớờợởỡ]";
            }
            if (c == 'i')
            {
                tmp = "[iíìịỉĩ]";
            }
            if (c == 'u')
            {
                tmp = "[uúùụủũưứừựửữ]";
            }
            if (c == 'd')
            {
                tmp = "[dđ]";
            }
            if (c == 'y')
            {
                tmp = "[ýyỳỷỹ]";
            }
            searchKey += tmp;
        }
        return searchKey;
    }
    #endregion

    public static string FormatMoney(object money)
    {
        if (money == null) return "Liên hệ";

        if (money.ToString() == "0")
        {
            return "Liên hệ";
        }

        double dMoney = 0;
        double.TryParse(money.ToString(), out dMoney);
        if (dMoney == 0) return "Liên hệ";
        return string.Format("{0:#,#}", dMoney).Replace(",", ".") + " đ";
    }

    public static string GetYoutubeVideoImage(object link, string order)
    {
        string format = "http://img.youtube.com/vi/{0}/{1}.jpg";
        if (link == null)
        {
            return "";
        }
        string str2 = link.ToString();
        if (str2.Contains("v="))
        {
            str2 = str2.Replace("v=", "@").Split(new char[] { '@' })[1];
            str2 = str2.Split(new char[] { '&' })[0];
        }
        if (str2.Contains("/v/"))
        {
            str2 = str2.Replace("/v/", "@").Split(new char[] { '@' })[1];
            str2 = str2.Split(new char[] { '&' })[0];
        }
        if (str2.Contains(".be/"))
        {
            str2 = str2.Replace(".be/", "@").Split(new char[] { '@' })[1];
            str2 = str2.Split(new char[] { '&' })[0];
        }
        return string.Format(format, str2, order);
    }

    public static string GetLinkImage(object folderUrl, object imageUrl)
    {

        string strImage = imageUrl.ToString().Split(';').Where(x => x != "").FirstOrDefault();

        return folderUrl + "/" + strImage;
    }
}
